<?php
/**
 * The view object.
 */
class View {
    /**
     * The view's parameters.
     * @var array
     */
    protected $params = array();
    /**
     * The template to load.
     * @var string
     */
    protected $template = '';
    /**
     * The renderer to use to render the template.
     * @var View_Renderer
     */
    protected $renderer = null;

    /**
     * Set the view renderer object.
     * @param View_Renderer $renderer
     */
    public function setRenderer(View_Renderer $renderer = null) {
        if($renderer !== null) {
            $this->renderer = $renderer;
        }
    }

    /**
     * Set the template file.
     * @param string $template
     */
    public function setTemplate($template) {
        $this->template = strtolower($template) . '.html';
    }

    /**
     * Get the template name.
     * @return string
     */
    public function getTemplate() {
        return $this->template;
    }

    /**
     * Magic set method to set parameters.
     * @param string $param
     * @param mixed $value
     */
    public function __set($param, $value) {
        $this->params[$param] = $value;
    }

    /**
     * Magic get method.
     * @param string $param
     * @return mixed
     */
    public function __get($param) {
        return $this->param[$param];
    }

    /**
     * Render the template. Create a standard renderer if one hasn't been set.
     * @param Page $page
     * @throws View_Exception
     */
    public function render(Page $page) {
        $path = './' . Framework::getViewsDirectory() . '/' . $this->template;
        if(!file_exists($path)) {
            throw new View_Exception("File '$path' does not exists.");
        }
        $file = file_get_contents($path);
        if($this->renderer === null) {
            $this->renderer = new View_Renderer_Standard();
        }
        $this->renderer->setParams($this->params);
        echo $this->renderer->render($file);
    }
}
?>